import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface ChatMessage {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  status?: 'sending' | 'error' | 'completed'
}

export interface ChatSession {
  id: string
  title: string
  messages: ChatMessage[]
  createdAt: Date
  updatedAt: Date
  enableImageGeneration: boolean
}

export const useChatStore = defineStore('chat', () => {
  // 状态
  const sessions = ref<ChatSession[]>([])
  const currentSessionId = ref<string | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const currentSession = computed(() => {
    return sessions.value.find(session => session.id === currentSessionId.value)
  })

  const currentMessages = computed(() => {
    return currentSession.value?.messages || []
  })

  const sessionCount = computed(() => sessions.value.length)

  // 从localStorage加载数据
  const loadFromStorage = () => {
    try {
      const stored = localStorage.getItem('chat-sessions')
      if (stored) {
        const parsed = JSON.parse(stored)
        sessions.value = parsed.map((session: any) => ({
          ...session,
          createdAt: new Date(session.createdAt),
          updatedAt: new Date(session.updatedAt),
          messages: session.messages.map((msg: any) => ({
            ...msg,
            timestamp: new Date(msg.timestamp)
          }))
        }))
      }
    } catch (error) {
      console.error('Failed to load chat sessions from storage:', error)
    }
  }

  // 保存到localStorage
  const saveToStorage = () => {
    try {
      localStorage.setItem('chat-sessions', JSON.stringify(sessions.value))
    } catch (error) {
      console.error('Failed to save chat sessions to storage:', error)
    }
  }

  // 创建新会话
  const createNewSession = (title?: string) => {
    const newSession: ChatSession = {
      id: `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      title: title || `Chat ${sessionCount.value + 1}`,
      messages: [],
      createdAt: new Date(),
      updatedAt: new Date(),
      enableImageGeneration: false
    }
    
    sessions.value.unshift(newSession)
    currentSessionId.value = newSession.id
    saveToStorage()
    
    return newSession
  }

  // 切换到指定会话
  const switchToSession = (sessionId: string) => {
    const session = sessions.value.find(s => s.id === sessionId)
    if (session) {
      currentSessionId.value = sessionId
    }
  }

  // 删除会话
  const deleteSession = (sessionId: string) => {
    const index = sessions.value.findIndex(s => s.id === sessionId)
    if (index !== -1) {
      sessions.value.splice(index, 1)
      
      // 如果删除的是当前会话，切换到第一个会话或创建新会话
      if (currentSessionId.value === sessionId) {
        if (sessions.value.length > 0) {
          currentSessionId.value = sessions.value[0].id
        } else {
          currentSessionId.value = null
        }
      }
      
      saveToStorage()
    }
  }

  // 更新会话标题
  const updateSessionTitle = (sessionId: string, title: string) => {
    const session = sessions.value.find(s => s.id === sessionId)
    if (session) {
      session.title = title
      session.updatedAt = new Date()
      saveToStorage()
    }
  }

  // 添加消息到当前会话
  const addMessage = (role: 'user' | 'assistant', content: string, status?: 'sending' | 'error' | 'completed') => {
    if (!currentSession.value) {
      createNewSession()
    }

    const message: ChatMessage = {
      id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      role,
      content,
      timestamp: new Date(),
      status
    }

    currentSession.value!.messages.push(message)
    currentSession.value!.updatedAt = new Date()
    
    // 如果是第一条用户消息，更新会话标题
    if (role === 'user' && currentSession.value!.messages.filter(m => m.role === 'user').length === 1) {
      const shortContent = content.length > 30 ? content.substring(0, 30) + '...' : content
      updateSessionTitle(currentSession.value!.id, shortContent)
    }
    
    saveToStorage()
    return message
  }

  // 更新消息
  const updateMessage = (messageId: string, updates: Partial<ChatMessage>) => {
    if (!currentSession.value) return

    const messageIndex = currentSession.value.messages.findIndex(m => m.id === messageId)
    if (messageIndex !== -1) {
      currentSession.value.messages[messageIndex] = {
        ...currentSession.value.messages[messageIndex],
        ...updates
      }
      currentSession.value.updatedAt = new Date()
      saveToStorage()
    }
  }

  // 清空当前会话
  const clearCurrentSession = () => {
    if (currentSession.value) {
      currentSession.value.messages = []
      currentSession.value.updatedAt = new Date()
      saveToStorage()
    }
  }

  // 设置图片生成开关
  const setImageGeneration = (enabled: boolean) => {
    console.log('setImageGeneration called with:', enabled)
    console.log('Current session before update:', currentSession.value)
    
    if (currentSession.value) {
      currentSession.value.enableImageGeneration = enabled
      currentSession.value.updatedAt = new Date()
      console.log('Updated session:', currentSession.value)
      saveToStorage()
    } else {
      console.error('No current session found!')
    }
  }

  // 获取图片生成状态
  const getImageGeneration = () => {
    return currentSession.value?.enableImageGeneration || false
  }

  // 初始化
  const initialize = () => {
    loadFromStorage()
    
    // 如果没有会话，创建一个默认会话
    if (sessions.value.length === 0) {
      const defaultSession = createNewSession('Welcome Chat')
      console.log('创建默认会话:', defaultSession)
    } else if (!currentSessionId.value) {
      currentSessionId.value = sessions.value[0].id
      console.log('设置当前会话ID:', currentSessionId.value)
    }
    
    console.log('初始化完成，会话数量:', sessions.value.length)
    console.log('当前会话ID:', currentSessionId.value)
  }

  return {
    // 状态
    sessions,
    currentSessionId,
    isLoading,
    
    // 计算属性
    currentSession,
    currentMessages,
    sessionCount,
    
    // 方法
    createNewSession,
    switchToSession,
    deleteSession,
    updateSessionTitle,
    addMessage,
    updateMessage,
    clearCurrentSession,
    setImageGeneration,
    getImageGeneration,
    initialize,
    saveToStorage,
    loadFromStorage
  }
})
